from django import http
from django.core.cache import cache
from django.shortcuts import render

# Create your views here.
from django.views import View

from areas.models import Area
from meiduo_mall.utils.response_code import RETCODE
import logging

logger = logging.getLogger('django')


class ProvinceAreasView(View):
    '''省地区视图'''

    def get(self, request):
        '''
        获取省的接口
        :param request:
        :return:
        '''

        # 判断是否有缓存
        province_list = cache.get('province_list')

        if not province_list:
            try:
                province_model_list = Area.objects.filter(parent__isnull=True)

                # 创建空表返回省份
                province_list = []
                for province_model in province_model_list:
                    province_list.append({'id': province_model.id,
                                          'name': province_model.name})

                # 增加缓存
                cache.set('province_list', province_list, 3600)

            except Exception as e:

                # 请求省份错误
                return http.JsonResponse({'code': RETCODE.DBERR,
                                          'errmsg': '省份数据错误'})

        # 返回请求
        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'OK',
                                  'province_list': province_list})


class SubAreasView(View):
    """子级地区：市和区县"""

    def get(self, request, pk):
        '''
        提供市或区地区数据
        1.查询市或区数据
        2.序列化市或区数据
        3.响应市或区数据
        4.补充缓存数据
        :param request:
        :param pk: 父级地区的pk
        :return:
        '''
        sub_data = cache.get('sub_data' + pk)
        if not sub_data:
            try:
                sub_model_list = Area.objects.filter(parent=pk)
                parent_model = Area.objects.get(id=pk)


                sub_list = []

                for sub_model in sub_model_list:
                    sub_list.append({'id': sub_model.id,
                                     'name': sub_model.name})

                sub_data = {
                    'id': parent_model.id,  # pk
                    'name': parent_model.name,
                    'subs': sub_list}
                cache.set('sub_data' + pk, sub_data, 3600)
            except Exception as e:
                logger.error(e)
                return http.JsonResponse({'code': RETCODE.DBERR,
                                          'errmsg': '城市或区县数据错误'})

        # 3.响应市或区数据
        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'OK',
                                  'sub_data': sub_data})
